package controllers;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import models.Event;
import models.User;

import org.codehaus.jackson.node.ObjectNode;

import play.data.Form;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security;

@Security.Authenticated(Secure.class)
public class Events extends Controller {

    static Form<Event> eventForm;

    public static Result index() {
        return ok(views.html.User.Event.index.render());
    }

    public static Result listEvents() {
        return ok(views.html.User.Event.listEvents.render(Event.find.all(), session().get("keyId"),
                session().get("vCode")));
    }

    public static Result addEventForm(long id) {
        eventForm = Form.form(Event.class);
        // Fill form with values
        if (id > 0) {
            eventForm = eventForm.fill(Event.find.byId(id));
        }
        return ok(views.html.User.Event.addEvent.render(eventForm, ""));
    }

    public static Result addEvent() {
        Form<Event> filledEventForm = eventForm.bindFromRequest();

        // Remove wrong errors
        filledEventForm.errors().remove("author");

        if (filledEventForm.hasErrors()) {
            // Return error if empty fields
            return ok(views.html.User.Event.addEvent.render(filledEventForm, ""));
        } else {
            Event event = (!filledEventForm.field("id").value().isEmpty()) ? Event.find.byId(Long
                    .valueOf(filledEventForm.field("id").value())) : new Event();

            String strStartDate = filledEventForm.field("startDate").value();
            String strEndDate = filledEventForm.field("endDate").value();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            try {
                ObjectNode result = Json.newObject();
                result.put("redirect", true);
                Date startDate = sdf.parse(strStartDate);
                Date endDate = sdf.parse(strEndDate);
                event.setName(filledEventForm.field("name").value());
                event.setDescription(filledEventForm.field("description").value());
                event.setPhone(filledEventForm.field("phone").value());
                event.setStartDate(startDate);
                event.setEndDate(endDate);

                if (event.getId() == null) {
                    event.setUser(User.find.byId(Long.valueOf(session().get("user"))));
                    event.save();
                } else {
                    event.update();
                }

                return ok(result);
            } catch (ParseException e) {
                return ok(views.html.User.Event.addEvent.render(filledEventForm,
                        "<p class='error'>Error during event creation. Please verify date format !</p>"));
            }
        }
    }
}